<?php

namespace app\api\controller;

use think\facade\Request;
use app\common\Common;
use app\api\service\KwaiService;
use app\common\Error;
use think\facade\Db;

class Kwai extends Base
{
    private $service;

    public function __construct(KwaiService $service)
    {
        $this->service = $service;
    }

    // 快手小程序登录
    public function login()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Kwai::class)->scene('login')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }
        
        $data = $this->service->kwaiUserLogin($params);

        if (empty($data) || !empty($data['message'])) {
            $message = !empty($data['message']) ? $data['message'] : Error::FAIL_AUTHORIZED_lOGIN;
            return Common::fail($message);
        }

        return Common::success($data);
    }

    // 快手小程序支付(微信和支付宝)
    public function placeOrder()
    {
        $params = Request::param();

        try {
            validate(\app\api\validate\Kwai::class)->scene('place_order')->check($params);
        } catch (\Exception $e) {
            return Common::fail($e->getError());
        }

        $data = $this->service->advancePaymentOrder($params, $this->getUserID());
        if (empty($data) || !empty($data['message'])) {
            $message = !empty($data['message']) ? $data['message'] : Error::FAIL_AUTHORIZED_lOGIN;
            return Common::fail($message);
        }

        return Common::success($data);
    }

    // 回调（用于接收抖音异步通知消息，需要传入 https 公网可访问的网页地址）
    public function callback()
    {
        $params = Request::param();

        $data = $this->service->payCallBack($params);
        echo json_encode($data);
        exit();
    }

    // 快手同步异常订单同步
    public function sync()
    {
        $where[] = ['settlement_status', '=', 2];
        $where[] = ['sync_status', '=', 1];
        $where[] = ['created_at', '<', 1704495000];
        $where[] = ['settlement_error_msg', '=', '当前有正在结算中的订单'];
        // $where[] = ['id', '<', 49669];
        $orderData = Db::name('kwai_order_sync_settlement')->where($where)->field('id, order_no, uid')->order('id desc')->limit(500)->select()->toArray();
        // $orderData = Db::name('kwai_order_sync_settlement')->where(['order_no' => '1712586440632459264'])->field('id, order_no, uid')->order('id desc')->limit(400)->select()->toArray();
        // dump($orderData);die;
        // $orderNo = '1721234581824479232';
        $appletData = Db::name('applet')->where(['id' => 27])->field('app_id, app_secret')->find();
        $accessToken = Common::getKwaiAppletAccessToken($appletData['app_id'], $appletData['app_secret']);
        $url = 'https://open.kuaishou.com/openapi/mp/developer/epay/settle?app_id='.$appletData['app_id'].'&access_token='.$accessToken;

        $paySaveData = $settlementData = [];

        foreach ($orderData as $key => $value) {

            $settleNo = date('YmdHis') . rand(1000, 10000);

            $requestData = [
                'out_order_no' => $value['order_no'],
                'out_settle_no' => $settleNo,
                'reason' => '已支付订单结算',
                'notify_url' => 'https://' . config('app.app_host') . '/admin/finance/settlementCallback'
            ];

            $sign = self::sign($requestData, $appletData);
            $requestData['sign'] = $sign;

            $prepayData = Common::curlRequest($url, 'POST', json_encode($requestData), ['Content-Type: application/json']);

            $result = json_decode($prepayData, true);

            if (isset($result['result']) && $result['result'] == 1) {
                $PayId = Db::name('pay_record')->where(['order_no' => $value['order_no']])->value('id');
                $paySaveData[] = [
                    'id' => $PayId,
                    'is_settlement' => 1,
                    'updated_at' => time()
                ];
                Db::name('kwai_order_sync_settlement')->where(['order_no' => $value['order_no']])->update([
                    'settlement_status' => 1,
                    'settle_no' => $result['settle_no'],
                    'updated_at' => time()
                ]);

            } else {

                Db::name('kwai_order_sync_settlement')->where(['order_no' => $value['order_no']])->update([
                    'settlement_status' => 2,
                    'settlement_error_msg' => $result['error_msg'],
                    'settle_no' => $settleNo,
                    'updated_at' => time()
                ]);

            }

        }
        $model = new \app\model\PayRecord();
        $bool = $model->saveAll($paySaveData);

        echo json_encode($result);
        exit();
    }

    // 签名
    public function sign($body = [], $appletData = [])
    {
        $body['app_id'] = $appletData['app_id'];
        ksort($body);
        $string = '';
        foreach ($body as $key => $value) {
            $string .= $key.'='.$value.'&';
        }
        $string = substr($string, 0, strlen($string) - 1).$appletData['app_secret'];
        return md5($string);
    }
}